package com.qiongqi.datadir.config;

import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.DisallowedMethodsHandler;
import io.undertow.util.HttpString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class UndertowWebServerCustomizerConfig implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {

    @Override
    public void customize(UndertowServletWebServerFactory factory) {
        factory.addDeploymentInfoCustomizers(deploymentInfo -> {
            deploymentInfo.addInitialHandlerChainWrapper(new HandlerWrapper() {
                @Override
                public HttpHandler wrap(HttpHandler handler) {

                    //禁止三个方法TRACE也是不安全的
                    log.warn("disable HTTP methods: CONNECT/TRACE/TRACK");
                    HttpString[] disallowedHttpMethods = {
                            HttpString.tryFromString("CONNECT"),
                            HttpString.tryFromString("TRACE"),
                            HttpString.tryFromString("TRACK")
                    };
                    return new DisallowedMethodsHandler(handler, disallowedHttpMethods);
                }
            });
        });
    }
}
